package com.goldgov.code.template.model;

import java.io.IOException;
import java.io.Writer;
import java.util.List;
import java.util.Map;

import com.goldgov.code.template.point.CodePoint;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

public class CodePointModel implements TemplateDirectiveModel {
	
	private final List<CodePoint> codePointList;

	public CodePointModel(List<CodePoint> codePoint) {
		this.codePointList = codePoint;
	}

	@Override
	public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
			throws TemplateException, IOException {
		Object name = params.get("name");
		Object defTextObj = params.get("default");
		Object preObj = params.get("pre");
		Object postObj = params.get("post");
		String pointName = String.valueOf(name);
		
		Writer out = env.getOut();
		boolean hasOut = false;
		for (CodePoint point : codePointList) {
			if(point.getPointName().equals(pointName)) {
				out.write(point.getCodes());
				hasOut = true;
			}
		}
		if(preObj != null) {
			out.write("        " + preObj + "\r\n");
		}
		
		if(!hasOut) {
			String comment = "";
			if(false) {
				comment = "//TODO 代码尚未实现，请在实现后删除本行注释";
			}
			String defText = defTextObj == null ? "" : defTextObj.toString();
			out.write("        " + comment + "\r\n");
			out.write("        " + defText + "\r\n");
		}
		
		if(postObj != null) {
			out.write("        " + postObj + "\r\n");
		}
	}

}
